package org.jash.shop2202.user

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hyphenate.chat.ChatClient
import kotlinx.coroutines.launch
import org.jash.shop2202.entity.User
import org.jash.shop2202.mvvm.BaseViewModel
import com.hyphenate.helpdesk.callback.Callback
import org.jash.shop2202.entity.Res
import org.jash.shop2202.utils.logging
import kotlin.reflect.KSuspendFunction1


class LoginViewModel:BaseViewModel() {
    val successLiveData by lazy { MutableLiveData<User>() }
    private val repo:LoginRepo by lazy { LoginRepo() }
    fun login(map:Map<String, String>) {
        viewModelScope.launch {
            try {
                val res = repo.login(map)
                ChatClient.getInstance().login(map["username"], map["password"], object : Callback {
                    override fun onSuccess() {
                        logging("登录成功")
                    }

                    override fun onError(code: Int, error: String?) {
                        logging("登录失败, 原因: $error")
                    }

                    override fun onProgress(progress: Int, status: String?) {
                    }
                })

                if (res.code == 200) {
                    successLiveData.postValue(res.data)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }

}